package com.diandi.signature.util;

import freemarker.cache.FileTemplateLoader;
import freemarker.cache.TemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.*;
import java.util.Map;

/**
 * Created by Administrator on 2017/6/1.
 */
public class CreateWordUtil {

    public static String createWord(String tempName, String tempPath, Map<String, Object> param, String createFileName, String surfix) {
        try {
            //模板的路径
            File fir = new File(tempPath);

            //生成文件的路径及文件名。
            File outFile = File.createTempFile(createFileName, surfix);

            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8"));

            // 使用FileTemplateLoader
            //指定模板路径
            TemplateLoader templateLoader = null;
            templateLoader = new FileTemplateLoader(fir);

            Configuration cfg = new Configuration();
            cfg.setTemplateLoader(templateLoader);
            Template t = cfg.getTemplate(tempName, "UTF-8");

            t.process(param, out);
            out.flush();
            out.close();
            return outFile.getAbsolutePath();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 创建目录
     *
     * @param destDirName 目标目录名
     * @return 目录创建成功放回true，否则返回false
     */
    public static File createDir(String destDirName) {
        File dir = new File(destDirName);
        if (dir.exists()) {
            System.out.println("创建目录" + destDirName + "失败，目标目录已存在！");
            return dir;
        }
        if (!destDirName.endsWith(File.separator)) {
            destDirName = destDirName + File.separator;
        }
        // 创建目标目录
        if (dir.mkdir()) {
            System.out.println("创建目录" + destDirName + "成功！");
            return dir;
        } else {
            System.out.println("创建目录" + destDirName + "失败！");
            return null;
        }
    }
}
